//
//  CustomerAVPlayerView.m
//  网络视频播放多段缓存
//
//  Created by apple on 16/5/26.
//  Copyright © 2016年 cheniue. All rights reserved.
//

#import "CustomerAVPlayerView.h"
#import "AFNetworking.h"
@implementation CustomerAVPlayerView

-(instancetype)initWithFrame:(CGRect)frame urlPath:(NSString *)urlPath isFileUrl:(BOOL)isFileUrl
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self setBackgroundColor:[UIColor blackColor]];
        _playView = [[UIView alloc]initWithFrame:self.bounds];
        [self addSubview:_playView];
        
        _controlView = [[CustomerControlView alloc]initWithFrame:self.bounds];
        [_controlView setAlpha:1.0f];
        
        [_controlView.playButton addTarget:self action:@selector(changePlayState:) forControlEvents:UIControlEventTouchUpInside];
        
        [_controlView.scaleButton addTarget:self action:@selector(changeToFullScreen) forControlEvents:UIControlEventTouchUpInside];
        
        [_controlView.backButton addTarget:self action:@selector(handleBackBtn) forControlEvents:UIControlEventTouchUpInside];
        
        [_controlView.suxiaButton addTarget:self action:@selector(changeToSmallScreen) forControlEvents:UIControlEventTouchUpInside];
        
        typeof(self) __weak weakself = self;
        
        [_controlView.progressSlider setChangeBlock:^(float progress){
            typeof(weakself) __strong strongself = weakself;
            [strongself changeProgress:progress];
        }];
        NSString *sttr = urlPath;

        if (isFileUrl) {
            _playItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:sttr]];
        } else {
            _playItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:sttr]];
        }
        
//        }
        
        [[NSNotificationCenter defaultCenter] addObserver:self
         
                                                 selector:@selector(handleBackBtn)
         
                                                     name:AVPlayerItemDidPlayToEndTimeNotification
         
                                                   object:self.playItem];

        _player = [AVPlayer playerWithPlayerItem:_playItem];
        [_player setVolume:0.5f];
        
        [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time)
         {
             
             __strong __typeof(weakself) strongSelf = weakself;
             if (!strongSelf.controlView.progressSlider.onControl)
             {
                 if (strongSelf.playItem.currentTime.timescale != 0.0f && strongSelf.playItem.duration.timescale != 0.0f)
                 {
                     float time = strongSelf.playItem.currentTime.value/strongSelf.playItem.currentTime.timescale;
                     float totalTime = strongSelf.playItem.duration.value / strongSelf.playItem.duration.timescale;
                     
                     if (totalTime > 0.0f)
                     {
                         float current = time/totalTime;
                         [strongSelf.controlView.progressSlider setValue:current];
                     }
                 }
             }
             
             [strongSelf setCurrentDate];
         }];
        
        [_delegate setDataBlock:^(NSArray<__kindof LocationFileInfo*>* dataRanges,VideoResourceSupport *sp)
         {
             __strong __typeof(weakself) strongSelf = weakself;
             [strongSelf drawCacheRanges:dataRanges];
         }];
        
        
        [self.controlView.titleLabel setText:@"视频标题"];
        
        _playLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
        [_playLayer setFrame:_playView.bounds];
        [_playView.layer addSublayer:_playLayer];
        
        _isFullScreen = NO;
        
        _smallRect = frame;
        
        //        _showControl = NO;
        [self setShowControl:YES];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showControlView:)];
        [tapGesture setNumberOfTapsRequired:1];
        [tapGesture setNumberOfTouchesRequired:1];
        [self addGestureRecognizer:tapGesture];
        self.tag = 1234567890;
    }
    
    
    if(self.isCycleplay)
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:_player.currentItem];
    }
    if(self.isMute)
    {
        _player.volume = 0;
    }
    return self;
}


-(instancetype)initWithFrame:(CGRect)frame urlPath:(NSString *)urlPath isFileUrl:(BOOL)isFileUrl isCycleplay:(BOOL)isCycleplay isMute:(BOOL)isMute isShowControl:(BOOL)isShowControl
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self setBackgroundColor:[UIColor blackColor]];
        _playView = [[UIView alloc]initWithFrame:self.bounds];
        [self addSubview:_playView];
        
        _controlView = [[CustomerControlView alloc]initWithFrame:self.bounds];
        [_controlView setAlpha:1.0f];
        
        [_controlView.playButton addTarget:self action:@selector(changePlayState:) forControlEvents:UIControlEventTouchUpInside];
        
        [_controlView.scaleButton addTarget:self action:@selector(changeToFullScreen) forControlEvents:UIControlEventTouchUpInside];
        
        [_controlView.backButton addTarget:self action:@selector(handleBackBtn) forControlEvents:UIControlEventTouchUpInside];
        
        [_controlView.suxiaButton addTarget:self action:@selector(changeToSmallScreen) forControlEvents:UIControlEventTouchUpInside];
        
        typeof(self) __weak weakself = self;
        
        [_controlView.progressSlider setChangeBlock:^(float progress){
            typeof(weakself) __strong strongself = weakself;
            [strongself changeProgress:progress];
        }];
        NSString *sttr = urlPath;
        
        if (isFileUrl) {
            _playItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:sttr]];
        } else {
            _playItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:sttr]];
        }
        
        //        }
        
        [[NSNotificationCenter defaultCenter] addObserver:self
         
                                                 selector:@selector(handleBackBtn)
         
                                                     name:AVPlayerItemDidPlayToEndTimeNotification
         
                                                   object:self.playItem];
        
        _player = [AVPlayer playerWithPlayerItem:_playItem];
        [_player setVolume:0.5f];
        
        [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time)
         {
             
             __strong __typeof(weakself) strongSelf = weakself;
             if (!strongSelf.controlView.progressSlider.onControl)
             {
                 if (strongSelf.playItem.currentTime.timescale != 0.0f && strongSelf.playItem.duration.timescale != 0.0f)
                 {
                     float time = strongSelf.playItem.currentTime.value/strongSelf.playItem.currentTime.timescale;
                     float totalTime = strongSelf.playItem.duration.value / strongSelf.playItem.duration.timescale;
                     
                     if (totalTime > 0.0f)
                     {
                         float current = time/totalTime;
                         [strongSelf.controlView.progressSlider setValue:current];
                     }
                 }
             }
             
             [strongSelf setCurrentDate];
         }];
        
        [_delegate setDataBlock:^(NSArray<__kindof LocationFileInfo*>* dataRanges,VideoResourceSupport *sp)
         {
             __strong __typeof(weakself) strongSelf = weakself;
             [strongSelf drawCacheRanges:dataRanges];
         }];
        
        
        [self.controlView.titleLabel setText:@"视频标题"];
        
        _playLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
        [_playLayer setFrame:_playView.bounds];
        [_playView.layer addSublayer:_playLayer];
        
        _isFullScreen = NO;
        
        _smallRect = frame;
        
        //        _showControl = NO;
//        [self setShowControl:isShowControl];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showControlView:)];
        [tapGesture setNumberOfTapsRequired:1];
        [tapGesture setNumberOfTouchesRequired:1];
        [self addGestureRecognizer:tapGesture];
        self.tag = 1234567890;
        if(isCycleplay)
        {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:_player.currentItem];
        }
        if(isMute)
        {
            _player.volume = 0;
        }
    }
    return self;
}




- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    [[NSNotificationCenter defaultCenter]
     removeObserver:_playItem];
   
}

/**
 *  播放完成通知
 *
 *  @param notification 通知对象
 */
-(void)playbackFinished:(NSNotification *)notification{
    NSLog(@"视频播放完成.");
    // 播放完成后重复播放
    // 跳到最新的时间点开始播放
    [self.player seekToTime:CMTimeMake(0, 1)];
    [self.player play];
}


-(void)drawCacheRanges:(NSArray<__kindof LocationFileInfo*>*)dataRanges
{
    NSMutableArray *ranges = [NSMutableArray array];
    for (LocationFileInfo *info in dataRanges)
    {
        float startX = (1.0f*info.startLocation/_delegate.videoLength);
        float lineWidth = (1.0f*info.dataLength/_delegate.videoLength);
        
        [ranges addObject:[[CacheRange alloc] initWithStartLocation:startX cacheLength:lineWidth]];
    }
    
    [_controlView.progressSlider setRanges:ranges];
}
-(void)changePlayState:(UIButton*)sender
{
    [_controlView setPlayButtonSelected:!sender.selected];
    if (_controlView.playButton.selected)
    {
        [_player play];
    }
    else
    {
        [_player pause];
    }
}
-(void)setCurrentDate
{
    float time = self.playItem.currentTime.value/self.playItem.currentTime.timescale;
    float totalTime = self.playItem.duration.value / self.playItem.duration.timescale;
    if (time == 1) {
        if ([self.Delegate respondsToSelector:@selector(videoIsStartToPlay)]) {
            [self.Delegate videoIsStartToPlay];
        }

    }

    [self.controlView.timeLabel setText:[NSString stringWithFormat:@"%@ / %@",[self stringFromTime:time],[self stringFromTime:totalTime]]];
}
-(NSString*)stringFromTime:(float)time
{
    long videocurrent = ceil(time);
    
    NSString *str = @"";
    
    if (videocurrent < 3600)
    {
        str =  [NSString stringWithFormat:@"%02li:%02li",lround(floor(videocurrent/60.f)),lround(floor(videocurrent/1.f))%60];
    }
    else
    {
        str =  [NSString stringWithFormat:@"%02li:%02li:%02li",lround(floor(videocurrent/3600.f)),lround(floor(videocurrent%3600)/60.f),lround(floor(videocurrent/1.f))%60];
    }
    
    return str;
}
- (void)changeProgress:(float)progress
{
    float seconds = _playItem.duration.value / _playItem.duration.timescale*progress;
    [_player pause];
    typeof(_player) __weak weakplayer = _player;
    [_player seekToTime:CMTimeMakeWithSeconds(seconds, NSEC_PER_SEC) completionHandler:^(BOOL finished)
    {
        typeof(weakplayer) __strong strongplayer = weakplayer;
        [strongplayer play];
        
    }];
}
-(void)layoutSubviews
{
    [super layoutSubviews];
    [_playView setFrame:self.bounds];
//    [_playLayer setFrame:_playView.bounds];
    [_controlView setFrame:self.bounds];
}

-(void)showControlView:(UIGestureRecognizer*)gesture
{
    if (gesture.state == UIGestureRecognizerStateEnded)
    {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(dissmissControlView) object:nil];
        
        if (!_showControl)
        {
            [self setShowControl:YES];
        }
    }
}
-(void)dissmissControlView
{
    if (!_controlView.onControl)
    {
        [self setShowControl:NO];
    }
}
-(void)setShowControl:(BOOL)showControl
{
    [self addSubview:_controlView];

//    _showControl = showControl;
//    if (_showControl)
//    {
//        [UIView animateWithDuration:0.5f animations:^{
//            [_controlView setAlpha:1.0f];
//            [self addSubview:_controlView];
//        } completion:^(BOOL finished) {
//            _showControl = YES;
//
//            [self performSelector:@selector(dissmissControlView) withObject:nil afterDelay:2.0f];
//        }];
//    }
//    else
//    {
//        [UIView animateWithDuration:0.5f animations:^{
//            [_controlView setAlpha:0.0f];
//        } completion:^(BOOL finished) {
//            [_controlView removeFromSuperview];
//            _showControl = NO;
//        }];
//    }
}

- (void)handleBackBtn {
    if ([self.Delegate respondsToSelector:@selector(clickBackBtnVideoPlay)]) {
        [self.Delegate clickBackBtnVideoPlay];
    }
}

-(void)setSmallRect:(CGRect)smallRect
{
    _smallRect = smallRect;
    if (!_isFullScreen)
    {
        [self setTransform:CGAffineTransformIdentity];
        [self setFrame:_smallRect];
        
        [self showFull:NO];
        
        [[self getPlayerViewVC] setNeedsStatusBarAppearanceUpdate];

    }
}

-(void)changeToSmallScreen
{
    _isFullScreen = NO;
    [self setTransform:CGAffineTransformIdentity];
    [self setFrame:_smallRect];
    
    [self showFull:NO];
    
    [[self getPlayerViewVC] setNeedsStatusBarAppearanceUpdate];

}

-(void)changeToFullScreen
{
    if (_isFullScreen)
    {
        _isFullScreen = NO;
        [self setTransform:CGAffineTransformIdentity];
        [self setFrame:_smallRect];
        
        [self showFull:NO];
    }
    else
    {
        _isFullScreen = YES;
        
        if (_playItem.presentationSize.width > _playItem.presentationSize.height)
        {
            [self setFrame:[self frameFrom:self.superview.bounds]];
            [self setTransform:CGAffineTransformRotate(CGAffineTransformIdentity, M_PI_2)];
        }
        else
        {
            [self setTransform:CGAffineTransformIdentity];
            [self setFrame:self.superview.bounds];
        }
        
        [self showFull:YES];
        
        NSLog(@"%@",NSStringFromCGSize(_playItem.presentationSize));
    }
    
    [[self getPlayerViewVC] setNeedsStatusBarAppearanceUpdate];
}

-(CGRect)frameFrom:(CGRect)f
{
    CGRect rect = CGRectMake(f.origin.x+(f.size.width-f.size.height)/2.0f, f.origin.y-(f.size.width-f.size.height)/2.0f, f.size.height, f.size.width);
    return rect;
}

- (UIViewController *)getPlayerViewVC
{
    id page = self;
    
    for (int i=0; i<100; i++)
    {
        if ([page isKindOfClass:[UIViewController class]])
        {
            return page;
        }
        page = [page nextResponder];
    }
    
    return nil;
}

-(void)showFull:(BOOL)full
{
    if (full)
    {
        [_controlView.scaleButton setHidden:YES];
        [_controlView.topView setHidden:NO];
    }
    else
    {
        [_controlView.scaleButton setHidden:NO];
        [_controlView.topView setHidden:YES];
    }
}
@end
